﻿//-----------------------------------------------------------------------
// <copyright file="ConfigurationViewModel.cs" company="Ucodia">
//     Copyright © Ucodia. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.ViewModel;
using Microsoft.Win32;

namespace Ucodia.LocaliZune.SettingsEditor
{
    /// <summary>
    /// Represents a LocaliZune configuration view-model.
    /// </summary>
    public class ConfigurationViewModel : NotificationObject
    {
        /// <summary>
        /// A value indicating whether this view-model is being edited.
        /// </summary>
        private bool isEditing;

        /// <summary>
        /// LocaliZune exe configuration object.
        /// </summary>
        private Configuration configuration;

        /// <summary>
        /// LocaliZune configuration section.
        /// </summary>
        private LocaliZuneConfigurationSection configurationSection;

        /// <summary>
        /// The list of geographical locations.
        /// </summary>
        private List<GeographicalLocation> geographicalLocations;

        /// <summary>
        /// The save command.
        /// </summary>
        private DelegateCommand saveCommand;

        /// <summary>
        /// The file selection command.
        /// </summary>
        private DelegateCommand selectFileCommand;

        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigurationViewModel"/> class.
        /// </summary>
        public ConfigurationViewModel()
        {
            this.geographicalLocations = new List<GeographicalLocation>();
            string configurationFilename = "LocaliZune.exe.config";

            // Checking is configuration file exists
            if (!File.Exists(configurationFilename))
            {
                throw new InvalidOperationException("LocaliZune configuration file cannot be found.");
            }

            // Loading application configuration file
            ExeConfigurationFileMap configurationMapping = new ExeConfigurationFileMap();
            configurationMapping.ExeConfigFilename = configurationFilename;
            this.configuration = ConfigurationManager.OpenMappedExeConfiguration(configurationMapping, ConfigurationUserLevel.None);

            // Loading configuration section
            this.configurationSection = this.configuration.GetSection(LocaliZuneConfigurationSection.LocaliZuneConfigurationSectionSectionName) as LocaliZuneConfigurationSection;

            // Checking if configuration has been correctly loaded
            if (this.configurationSection == null)
            {
                throw new InvalidOperationException("Application settings are missing from configuration file.");
            }

            //// Building the list of geographical locations
            this.geographicalLocations = GeographicalLocationHelper.GetGeographicalLocations().ToList();
        }

        /// <summary>
        /// Gets or sets a value indicating whether this view-model is being edited.
        /// </summary>
        /// <value>
        ///     <c>true</c> if this instance is being edited; otherwise, <c>false</c>.
        /// </value>
        public bool IsEditing
        {
            get
            {
                return this.isEditing;
            }

            set
            {
                if (this.isEditing != value)
                {
                    this.isEditing = value;
                    this.RaisePropertyChanged(() => this.IsEditing);

                    this.SaveCommand.RaiseCanExecuteChanged();
                }
            }
        }

        /// <summary>
        /// Gets or sets the nation code.
        /// </summary>
        /// <value>
        /// The nation code.
        /// </value>
        public string NationCode
        {
            get
            {
                return this.configurationSection.Account.NationCode;
            }

            set
            {
                if (this.configurationSection.Account.NationCode != value)
                {
                    this.configurationSection.Account.NationCode = value;
                    this.RaisePropertyChanged(() => this.NationCode);

                    this.IsEditing = true;
                }
            }
        }

        /// <summary>
        /// Gets or sets the Zune Software application path.
        /// </summary>
        /// <value>
        /// The Zune Software application path.
        /// </value>
        public string ApplicationPath
        {
            get
            {
                return this.configurationSection.Software.ApplicationPath;
            }

            set
            {
                if (this.configurationSection.Software.ApplicationPath != value)
                {
                    this.configurationSection.Software.ApplicationPath = value;
                    this.RaisePropertyChanged(() => this.ApplicationPath);

                    this.IsEditing = true;
                }
            }
        }

        /// <summary>
        /// Gets or sets the LocaliZune shutdown delay.
        /// </summary>
        /// <value>
        /// The LocaliZune shutdown delay.
        /// </value>
        public int ShutdownDelay
        {
            get
            {
                return this.configurationSection.Settings.ShutdownDelay;
            }

            set
            {
                if (this.configurationSection.Settings.ShutdownDelay != value)
                {
                    this.configurationSection.Settings.ShutdownDelay = value;
                    this.RaisePropertyChanged(() => this.ShutdownDelay);

                    this.IsEditing = true;
                }
            }
        }

        /// <summary>
        /// Gets the geographical locations.
        /// </summary>
        public IEnumerable<GeographicalLocation> GeographicalLocations
        {
            get
            {
                return this.geographicalLocations.OrderBy(geo => geo.FriendlyName);
            }
        }

        /// <summary>
        /// Gets the save command.
        /// </summary>
        public DelegateCommand SaveCommand
        {
            get
            {
                if (this.saveCommand == null)
                {
                    this.saveCommand = new DelegateCommand(
                    () =>
                    {
                        this.configuration.Save();

                        this.IsEditing = false;
                    },
                    () =>
                    {
                        return this.IsEditing;
                    });
                }

                return this.saveCommand;
            }
        }

        /// <summary>
        /// Gets the file selection command.
        /// </summary>
        public DelegateCommand SelectFileCommand
        {
            get
            {
                if (this.selectFileCommand == null)
                {
                    this.selectFileCommand = new DelegateCommand(
                    () =>
                    {
                        OpenFileDialog dialog = new OpenFileDialog();
                        dialog.Filter = "Zune Software (Zune.exe)|Zune.exe";
                        dialog.InitialDirectory = System.IO.Path.GetDirectoryName(this.ApplicationPath);

                        bool? result = dialog.ShowDialog();

                        if (result.HasValue && result.Value)
                        {
                            this.ApplicationPath = dialog.FileName;
                        }
                    });
                }

                return this.selectFileCommand;
            }
        }
    }
}
